package com.xiaoxin_project.netty;

import com.xiaoxin_project.SpringUtil;
import com.xiaoxin_project.Util.JsonUtils;
import com.xiaoxin_project.enums.MsgActionEnum;
import com.xiaoxin_project.service.UserService;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于检测channel的心跳handler
 * 继承ChannelInboundHandlerAdapter从而不需要实现channelRead0方法
 *
 */
@Component
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    /**
     *当触发对应的用户事件时执行此方法
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
       //当有空闲(没有读写请求/写请求/读请求)的时候触发事件 判断channel是否处于空闲状态
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state() == IdleState.READER_IDLE) {
                System.out.println("处于读空闲请求。。。");
            }else if (event.state() == IdleState.WRITER_IDLE){
                System.out.println("处于读写闲请求。。。");
            }else if (event.state() == IdleState.ALL_IDLE){
                //此时读写都进入空闲 可能是飞行模式相关状态，清除chanel
                Channel channel = ctx.channel();
                //System.out.println("将要关闭channel===");
                //关闭不用的channel 以防资源浪费
                channel.close();
            }
        }
    }

}
